# -*- conding:utf-8 -*-

"""
@author:ym
@time:03-2021/3/10-
Copyright (c) All Rights Reserved, 2021/3/10.
可爱猫简单demo--python版本
"""
import json
import time
import requests
from flask import Flask, request, jsonify, render_template

# 使用Flask 快速开发
app = Flask(__name__)


@app.route('/debug', methods=['GET', 'POST'])
def debug():
    """
    /debug 请求路径
    支持的方法：GET、POST
    :return:
    """
    ret = {
        "msg": "success",
        "code": 200
    }
    # get json message
    data = request.get_data()
    data = json.loads(data)
    robot_wxid = data["robot_wxid"]
    msg = data["msg"]
    from_wxid=data["from_wxid"]
    if robot_wxid!=from_wxid:
       # 如果不是来自自己的消息，复读
        sendMessage(robot_wxid,msg)
    print(data)
    # 数据的具体字段以及意思，请查看文档
    # return json
    return jsonify(ret)


@app.errorhandler(404)
def page_not_found(error):
    ret = {
        "msg": "error!",
        "code": 200
    }
    # 返回json请求
    return jsonify(ret)


def sendMessage(robot_wxid, msg):
    """
    
    """
    headers = {
        'Content-Type': 'application/json'
    }
    url = "http://127.0.0.1:8090/"

    payload = json.dumps({
      # 发送文本事件
      "event": "SendTextMsg",
      # 机器人ID
      "robot_wxid": "wxid_8p1bw9yuhxm122",
      # 发送人的id
      "to_wxid": "wxid_8p1bw9yuhxm122",
      # 消息
      "msg": msg
    })
    response = requests.request("POST", url, headers=headers, data=payload)


app.run(
    # 设置服务开启的IP地址 外网请使用0.0.0.0
    host='127.0.0.1',
    # 端口
    port=5000,
    debug=True
)
